package com.sunny.service.v2;

import com.sunny.service.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.Map;

/**
 * @author Sunny
 * @date 2020/2/6
 */
public class CustomProcessHandler extends ChannelInboundHandlerAdapter {

    private Map<String, Object> serviceBeanMap;

    public CustomProcessHandler(Map<String, Object> serviceBeanMap) {
        this.serviceBeanMap = serviceBeanMap;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RpcRequest request = (RpcRequest) msg;
        Object invoke = invoke(request);
        ctx.writeAndFlush(invoke);
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
    }

    /**
     * 动态代理调用本地的服务
     *
     * @param rpcRequest 请求信息
     */
    Object invoke(RpcRequest rpcRequest) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        String className = rpcRequest.getClassName();
        String version = rpcRequest.getVersion();

        //判断版本号
        if (!StringUtils.isEmpty(version)) {
            className += "-" + version;
        }

        Object serviceBean = serviceBeanMap.get(className);

        if (serviceBean == null) {
            throw new RuntimeException("service not found! " + className);
        }

        Object[] args = rpcRequest.getParameters();

        Method method = null;
        Class<?> clazz = Class.forName(rpcRequest.getClassName());
        if (args != null) {
            Class<?>[] types = new Class[args.length];
            for (int i = 0; i < args.length; i++) {
                types[i] = args[i].getClass();
            }
            method = clazz.getMethod(rpcRequest.getMethodName(), types);
        } else {
            method = clazz.getMethod(rpcRequest.getMethodName());
        }
        return method.invoke(serviceBean, args);
    }
}
